#include "WHttpClientCommon.h"
#include <sstream>
#include <cctype>
#include <iomanip>

int64_t WHttpClientCommon::str2ll(const std::string &str, int64_t errValue)
{
    try {
        return std::stoll(str);
    } catch (const std::exception& e) {
        WLogw("WHttpClientCommon::str2ll error: %s", e.what());
        return errValue;
    }
}

std::string WHttpClientCommon::urlEncode(const std::string &input, bool isFormEncoded)
{
    std::ostringstream oss;
    oss << std::hex << std::uppercase;

    for (unsigned char c : input) {
        if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            oss << c;
        }
        else if (c == ' ') { // 空格处理：表单模式下转为+，否则转为%20
            oss << (isFormEncoded ? "+" : "%20");
        }
        else {  // 其他字符按UTF-8字节编码为%XX
            oss << "%" << std::setw(2) << std::setfill('0') << static_cast<int>(c);
        }
    }

    return oss.str();
}

std::string WHttpClientCommon::urlDecode(const std::string &input, bool isFormEncoded)
{
    std::string result;
    size_t i = 0;
    const size_t len = input.length();

    while (i < len) {
        if (input[i] == '%') {
            if (i + 2 >= len) {  // 检查是否有足够的字符进行解码
                return "";
            }

            // 解析两个十六进制字符
            int hex1 = hexToInt(input[i+1]);
            int hex2 = hexToInt(input[i+2]);
            if (hex1 == -1 || hex2 == -1) {
                return ""; // 无效的十六进制字符，解码失败
            }

            result += static_cast<char>((hex1 << 4) | hex2);
            i += 3; // 跳过%XX三个字符
        }
        else if (isFormEncoded && input[i] == '+') { // 表单模式下，+号转为空格
            result += ' ';
            i++;
        }
        else { // 检查是否有足够的字符进行解码
            result += input[i];
            i++;
        }
    }

    return result;
}

int WHttpClientCommon::hexToInt(char c)
{
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    return -1;
}


